<?php

namespace Tbf\Bundle\TestBundle\Logger;

use Doctrine\DBAL\Logging\SQLLogger;
use Psr\Log\LoggerInterface;

class DbalLogger implements SQLLogger
{
    protected $last_sql;
    protected $last_params;
    protected $last_time;
    protected $logger;

    public function __construct(LoggerInterface $logger = null)
    {
        $this->logger = $logger;
    }

    /**
     * Logs a SQL statement somewhere.
     *
     * @param  string $sql    The SQL to be executed.
     * @param  array  $params The SQL parameters.
     * @param  array  $types  The SQL parameter types.
     * @return void
     */
    public function startQuery($sql, array $params = null, array $types = null)
    {
        if (null === $this->logger) {
            return;
        }
        $this->last_sql = $sql;
        $this->last_params = $params;
        $this->last_time = microtime(true);

    }

    /**
     * Mark the last started query as stopped. This can be used for timing of queries.
     *
     * @return void
     */
    public function stopQuery()
    {
        if (null === $this->logger) {
            return;
        }
        $log = sprintf("%-10.3f %s",
            ((microtime(true) - $this->last_time) * 1000),
            $this->last_sql);
        $this->logger->debug($log,array($this->last_params));
    }

}
